import socket
import threading
import time
import random
def fn1(server):
    count = 1
    while True:
        conn, raddr = server.accept() #blocking

        threading.Thread(target=fn2, args=(conn,), name="r{}".format(count), daemon=True).start()
        count += 1


response_body = """\
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试网页</title>
</head>
<body>
    <h1 style="color:red">欢迎访问Magedu-{}</h1>
</body>
</html>
"""
response_header = """\
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: {}
X-Server: Vic.magedu.com
Connection: keep-alive

"""
# def get_response():
#     # with open("index.html", mode="rb",encoding="utf8") as f:
#     with open("index.html", mode="r") as f:
#         data = f.read()
#         print(type(data), data)
#         return data

def get_response():
    # with open("index.html", mode="rb",encoding="utf8") as f:
    with open("index.html", mode="rb") as template:
        data: bytes = template.read()
        #print(type(data), data)

        body: bytes = data.replace(b"{{}}",str(random.randint(1,100)).encode())
        return response_header.format(len(body)).replace("\r","\r\n").encode() + body

# def get_response():
#     html = response_body.format(random.randint(200,300)).encode()
#     response = response_header.format(len(html)).replace('\n','\r\n').encode() + html
#     return response



def fn2(conn: socket.socket):
    try:
        for i in range(3):
            data = conn.recv(4096)
            if not data:
                print(conn.getpeername(), "bye~~~")
                return

            print(type(data), data)
            conn.send(get_response())
            #conn.send(response)
    except Exception as e:
        print(e)
    finally:
        conn.close()


if __name__ == '__main__':
   # get_response().encode()
    server = socket.socket()
    server.bind(('127.0.0.1',9999))
    server.listen(1024) #non-blocking

    threading.Thread(target=fn1, args=(server,), name="accept", daemon=True).start()

    while True:
        time.sleep(5)
        print([t.name for t in threading.enumerate()])


    #server.close()